import os,sys,getopt
from PIL import Image, ImageDraw
from pathlib import  Path
from enum import Enum
import random

# 图片类型
class ImageType(Enum):
	JPG = 1
	PNG = 2

# 向图片某个随机像素位置添加1个1px的白点，达到异化图片的目的
def addDot(src_path, out_dir):
	path = Path(src_path)
	img = Image.open(str(path))
	size = img.size
	width = size[0]
	height = size[1]
	# 随机取1000个像素点，并生成对应颜色值(tuple)
	posArr = []
	colorArr = []
	for x in range(1000):
		pos = (random.randint(1, width-1), random.randint(1, height-1))
		#print(pos)
		posArr.append(pos)
		color = img.getpixel(pos)
		color_new = tuple(map(lambda x:x+1 if x<255 else x-1, color))
		colorArr.append(color_new)
	# 使用Draw.poiny()批量绘入图片
	drawer = ImageDraw.Draw(img)
	for i,pos in enumerate(posArr):
		#print(i,pos)
		drawer.point([pos], colorArr[i])

	img.save(str(Path(out_dir)/path.name))

# 参数解析
src_dir = '' # 源图片所在目录
is_custom_dir = True # 开关参数，不指定则默认目标文件夹是生成好的SPU->SPU-3X4、SPU-100x100的目录结构;否则以src_dir参数指定的单层目录结构
out_dir = '' # 输出目录
opts, args = getopt.getopt(sys.argv[1:], 'd:o:s')
if len(opts)<1:
	print('Usage:脚本 -d <src path> -o <out_dir> [-s]\r\n参数说明：\r\n\t-s 开关参数,是否单层目录。默认是双层，设置则表示单层')
	exit()

for i in opts:
	if i[0]=='-d':
		src_dir = i[1]
	elif i[0]=='-s':
		is_custom_dir = False
	elif i[0]=='-o':
		out_dir = i[1]
	else:
		print(f'无法解析的命令行参数! {i[0]}')
		exit()

# 业务逻辑
if not os.path.isdir(src_dir) or not os.path.isdir(out_dir):
	print('源/输出 目录参数不是文件夹')
	exit()
if is_custom_dir:
	f1s = os.listdir(src_dir)
	for f1 in f1s:
		dir_path = Path(f'{src_dir}/{f1}')
		if dir_path.is_dir():
			f2s = os.listdir(dir_path)
			for f2 in f2s:
				if (f2.find('3x4')!=-1 or f2.find('100x100')!=-1):
					f2path = Path(f'{dir_path}/{f2}')
					f3s = os.listdir(f2path)
					for f3 in f3s:
						f3path = Path(f'{f2path}/{f3}')
						print(f3path)
						suffix = f3path.suffix
						suffix = suffix.lower()
						if suffix=='.jpg' or suffix=='.jpeg' or suffix=='.png':
							addDot(str(f3path), out_dir)
else:
	f1s = os.listdir(src_dir)
	for f1 in f1s:
		path = Path(f'{src_dir}/{f1}')
		suffix = path.suffix
		suffix = suffix.lower()
		if suffix=='.jpg' or suffix=='.jpeg' or suffix=='.png':
			print(path)
			addDot(str(path), out_dir)